import Phaser from "phaser";
import QGamePlugin from "./QGamePlugin";
import QGameFunction from "./QGameFunction";

declare module "phaser" {
    namespace GameObjects {
        interface Container {
            _qGameView?: QUIView;
        }
    }
}

export type QUIEvent = {
    type:
        | "click"
        | "mousedown"
        | "mouseup"
        | "mouseover"
        | "mouseout"
        | "wheel"
        | "drag";

    view: QUIView;
    event: Phaser.Input.Pointer;
};

export type QUIViewConfig = {
    [key: string]: any;
    name?: string;
    id?: string;
    class?: string;

    widthRatio?: number;
    heightRatio?: number;

    width?: number;
    height?: number;

    miniWidth?: number;
    miniHeight?: number;

    maxWidth?: number;
    maxHeight?: number;

    left?: number;
    top?: number;

    /**
     * left同时赋值，right优先级大于left
     * 计算方式：parentWidth - right - width
     **/
    right?: number | undefined;

    /**
     *  top同时赋值，bottom优先级大于top
     *  计算方式：parentHeight - bottom - height
     **/
    bottom?: number | undefined;

    /**
     * 显示方式
     * block: 显示
     * none: 隐藏
     */
    display?: "block" | "none";

    background?: number | string;

    imageUrl?: string;

    /**
     * 透明度
     * value: 0 - 1
     */
    alpha?: number;
    borderWidth?: number;
    borderColor?: number | string;

    /** 子组件间对其方式，布局类组件有效 */
    alignX?: "left" | "center" | "right";
    alignY?: "top" | "center" | "bottom";
    paddingTop?: number;
    paddingBottom?: number;
    paddingLeft?: number;
    paddingRight?: number;

    /** 组件之间的间距，布局类组件有效 */
    gap?: number;

    /** 禁止事件初始化 */
    prohibitEvent?: boolean;

    /**
     * 鼠标点击事件
     * @param e
     * @returns
     */
    onClick?: (e: QUIEvent) => void;

    /**
     * 鼠标按下事件
     * @param e
     * @returns
     **/
    onMouseDown?: (e: QUIEvent) => void;

    /**
     * 鼠标抬起事件
     * @param e
     * @returns
     */
    onMouseUp?: (e: QUIEvent) => void;

    /**
     * 鼠标移入事件
     * @param e
     * @returns
     */
    onMouseOver?: (e: QUIEvent) => void;

    /**
     * 鼠标移出事件
     * @param e
     * @returns
     */
    onMouseOut?: (e: QUIEvent) => void;

    /**
     * 鼠标滚轮事件
     * @param e
     * @returns
     **/
    onWheel?: (e: QUIEvent, deltaX?: number, deltaY?: number) => void;

    /**
     * 拖拽事件
     * @param e
     * @returns
     **/
    onDrag?: (e: QUIEvent, dragX: number, dragY: number) => void;
};

export class QUIView {
    /** 组件名称 */
    protected name: string = "QUIView";
    protected manage: QGamePlugin;
    protected uuid: string = QGameFunction.generateUUID();

    /** 组件的ID */
    protected id: string = "";
    protected class: string = "";

    /** 组件父级 */
    protected parent: QUIView | null = null;

    protected left: number = 0;
    protected top: number = 0;
    protected right: number | undefined = undefined;
    /** top同时赋值，bottom优先级大于top， 计算方式：parentHeight - bottom - height */
    protected bottom: number | undefined = undefined;
    protected width: number = 0;
    protected height: number = 0;
    protected miniWidth: number = 0;
    protected miniHeight: number = 0;
    protected maxWidth: number = 0;
    protected maxHeight: number = 0;

    protected widthRatio: number = 0;
    protected heightRatio: number = 0;

    protected alpha: number = 1;
    protected backgroundValue: number = 0x000000;
    protected tempBackgroundValue: number = 0x000000;

    protected zIndex: number = 0;

    protected borderWidth: number = 0;
    protected borderColor: number = 0;
    protected visible: boolean = true;

    /** 禁止事件触发 */
    protected prohibitEvent: boolean = false;

    /** 鼠标点击事件 */
    public onClick?: (e: QUIEvent) => void | undefined = undefined;
    /** 鼠标按下事件 */
    public onMouseDown?: (e: QUIEvent) => void | undefined = undefined;
    /** 鼠标抬起事件 */
    public onMouseUp?: (e: QUIEvent) => void | undefined = undefined;
    /** 鼠标移入事件 */
    public onMouseOver?: (e: QUIEvent) => void | undefined = undefined;
    /** 鼠标移出事件 */
    public onMouseOut?: (e: QUIEvent) => void | undefined = undefined;
    /** 鼠标悬停事件 */
    public onHover?: (e: QUIEvent) => void | undefined = undefined;

    /** 鼠标滚轮事件 */
    public onWheel?: (
        e: QUIEvent,
        deltaX: number,
        deltaY: number
    ) => void | undefined = undefined;

    /** 拖拽事件 */
    public onDrag?: (
        e: QUIEvent,
        dragX: number,
        dragY: number
    ) => void | undefined = undefined;

    protected childViews: QUIView[] = [];

    protected backgoundColor: Phaser.GameObjects.Graphics | null = null;
    protected mask: Phaser.GameObjects.Graphics | null = null;
    protected scene: Phaser.Scene;
    private container: Phaser.GameObjects.Container;
    // private viewContainer: Phaser.GameObjects.Container;

    private mouseDownTime: number = 0;

    private rectangle: Phaser.Geom.Rectangle | null = null;

    protected scrollWidth: number = 10;
    protected scrollBarBackgroundColor: number = 0x505050;
    protected scrollBarColor: number = 0x000000;

    protected scrollYBarBackground: Phaser.GameObjects.Rectangle | null = null;
    protected scrollYBar: Phaser.GameObjects.Rectangle | null = null;
    protected overflowY: "scroll" | "auto" | "hidden" = "auto";

    protected scrollXBarBackground: Phaser.GameObjects.Rectangle | null = null;
    protected scrollXBar: Phaser.GameObjects.Rectangle | null = null;
    protected scrollXBarBackgroundColor: number = 0x505050;
    protected scrollXBarColor: number = 0x000000;
    protected overflowX: "scroll" | "auto" | "hidden" = "auto";

    protected scrollLeft: number = 0;
    protected scrollTop: number = 0;

    /** 子组件间对其方式，布局类组件有效 */
    protected alignX: "left" | "center" | "right" = "left";
    protected alignY: "top" | "center" | "bottom" = "top";
    protected paddingTop: number = 0;
    protected paddingBottom: number = 0;
    protected paddingLeft: number = 0;
    protected paddingRight: number = 0;

    /** 组件之间的间距，布局类组件有效 */
    protected gap: number = 0;

    protected imageUrl: string = "";
    protected image: Phaser.GameObjects.Image | null = null;

    protected startLayout() {
        if (
            this.name == "QUIVerticalLayout" ||
            this.name == "QUIHorizontalLayout" ||
            this.name == "QUIGridLayout"
        ) {
            this.reLayout();
        }
    }

    set PaddingTop(value: number) {
        if (typeof value == "string") {
            value = parseInt(value);
        }
        this.paddingTop = value;
        this.startLayout();
    }

    set PaddingBottom(value: number) {
        if (typeof value == "string") {
            value = parseInt(value);
        }
        this.paddingBottom = value;
        this.startLayout();
    }

    set PaddingLeft(value: number) {
        if (typeof value == "string") {
            value = parseInt(value);
        }
        this.paddingLeft = value;
        this.startLayout();
    }

    set PaddingRight(value: number) {
        if (typeof value == "string") {
            value = parseInt(value);
        }
        this.paddingRight = value;
        this.startLayout();
    }

    get AlignX() {
        return this.alignX;
    }

    get AlignY() {
        return this.alignY;
    }
    get Gap() {
        return this.gap;
    }

    set AlignX(value: "left" | "center" | "right") {
        this.alignX = value;
        this.startLayout();
    }

    set AlignY(value: "top" | "center" | "bottom") {
        this.alignY = value;
        this.startLayout();
    }

    set Gap(value: number) {
        if (typeof value == "string") {
            value = parseInt(value);
        }
        this.gap = value;
        this.startLayout();
    }

    get UUID(): string {
        return this.uuid;
    }

    set Id(value: string) {
        this.id = value;
    }

    get Id(): string {
        return this.id;
    }

    set Class(value: string) {
        this.class = value;
    }

    get Class(): string {
        return this.class;
    }

    get Name() {
        return this.name;
    }

    set Alpha(value: number) {
        this.alpha = value;
        this.createBackgroundCor();
    }

    get Parent(): QUIView | null {
        return this.parent;
    }

    get MiniWidth(): number {
        return this.miniWidth;
    }
    set MiniWidth(value: number) {
        this.miniWidth = value;
        if (this.Width < this.miniWidth) {
            this.Width = this.miniWidth;
        }
    }
    get MiniHeight(): number {
        return this.miniHeight;
    }
    set MiniHeight(value: number) {
        this.miniHeight = value;
        if (this.Height < this.miniHeight) {
            this.Height = this.miniHeight;
        }
    }
    get MaxWidth(): number {
        return this.maxWidth;
    }
    set MaxWidth(value: number) {
        this.maxWidth = value;
        if (this.Width > this.maxWidth) {
            this.Width = this.maxWidth;
        }
    }

    set MaxHeight(value: number) {
        this.maxHeight = value;
        if (this.Height > this.maxHeight) {
            this.height = this.maxHeight;
        }
    }

    get MaxHeight(): number {
        return this.maxHeight;
    }

    // get Rectangle(): Phaser.Geom.Rectangle {
    //     return this.rectangle!;
    // }
    get BackgoundColor() {
        return this.backgroundValue;
    }

    constructor(
        scene: Phaser.Scene,
        manage: QGamePlugin,
        config?: QUIViewConfig
    ) {
        this.scene = scene;
        this.manage = manage;
        if (config) {
            this.settingConfig(config);
        }
        this.container = scene.add.container(this.left, this.top);

        this.container["_qGameView"] = this; // 存储对 QUIView 的引用 []

        // this.viewContainer = scene.add.container(0, 0);
        // this.container.add(this.viewContainer);

        /** 设置遮罩 */
        this.mask = scene.make.graphics();
        this.container.setMask(this.mask.createGeometryMask());
        // this.container.setMask(this.mask.createGeometryMask());

        if (this.image) {
            this.container.add(this.image);
        }

        this.eventSeting();
        this.reSize();
    }

    get ZIndex() {
        return this.zIndex;
    }

    set ZIndex(value: number) {
        this.zIndex = value;
        this.container.depth = this.zIndex;
    }

    get WorldX(): number {
        const matrix = this.container.getWorldTransformMatrix();
        return matrix.getX(0, 0);
    }
    get WorldY(): number {
        const matrix = this.container.getWorldTransformMatrix();
        return matrix.getY(0, 0);
    }
    protected onScrollAreaWheel(
        pointer: Phaser.Input.Pointer,
        deltaX: number,
        deltaY: number,
        deltaZ: number
    ) {}

    /**
     * 鼠标按下事件处理函数
     * @param e 事件对象
     */
    protected _pointerdown(e: Phaser.Input.Pointer) {}

    /**
     * 鼠标抬起事件处理函数
     * @param e 事件对象
     */
    protected _pointerup(e: Phaser.Input.Pointer) {}
    /**
     * 鼠标移入事件处理函数
     * @param e 事件对象
     */
    protected _pointerover(e: Phaser.Input.Pointer) {}

    /**
     * 鼠标移出事件处理函数
     * @param e 事件对象
     */
    protected _pointerout(e: Phaser.Input.Pointer) {}

    /**
     * 拖拽事件处理函数
     * @param e 事件对象
     * @param dragX 拖拽的x轴距离
     * @param dragY 拖拽的y轴距离
     */
    protected _drag(e: Phaser.Input.Pointer, dragX: number, dragY: number) {}

    disableInteractive() {
        this.container.disableInteractive();
    }

    enableInteractive() {
        this.container.setInteractive(true);
    }

    eventSeting() {
        if (this.rectangle === null) {
            this.rectangle = new Phaser.Geom.Rectangle(
                0,
                0,
                this.width,
                this.height
            );
        } else {
            this.rectangle.setTo(0, 0, this.width, this.height);
        }

        /** 不做事件相关初始化 */
        if (this.prohibitEvent) {
            return;
        }

        this.container.setInteractive(
            this.rectangle,
            Phaser.Geom.Rectangle.Contains
        );

        this.scene.input.setDraggable(this.container);

        /** 鼠标按下事件 */
        this.container.on("pointerdown", (e: Phaser.Input.Pointer) => {
            this.mouseDownTime = Date.now();
            if (this.onMouseDown !== undefined) {
                this.onMouseDown({
                    type: "mousedown",
                    view: this,
                    event: e,
                });
            }
            this._pointerdown(e);
        });

        /** 鼠标抬起事件 */
        this.container.on("pointerup", (e: Phaser.Input.Pointer) => {
            this._pointerup(e);
            if (this.onMouseUp !== undefined) {
                this.onMouseUp({
                    type: "mouseup",
                    view: this,
                    event: e,
                });
            }
            // 计算鼠标按下时间
            const mouseDownTime = Date.now() - this.mouseDownTime;
            if (mouseDownTime < 200) {
                if (this.onClick !== undefined) {
                    // 触发点击事件
                    this.onClick({
                        type: "click",
                        view: this,
                        event: e,
                    });
                }
            }
        });

        /** 鼠标移入事件 */
        this.container.on("pointerover", (e: Phaser.Input.Pointer) => {
            this._pointerover(e);
            if (this.onMouseOver !== undefined) {
                this.onMouseOver({
                    type: "mouseover",
                    view: this,
                    event: e,
                });
            }
        });

        /** 鼠标移出事件 */
        this.container.on("pointerout", (e: Phaser.Input.Pointer) => {
            this._pointerout(e);
            if (this.onMouseOut !== undefined) {
                this.onMouseOut({
                    type: "mouseout",
                    view: this,
                    event: e,
                });
            }
        });

        this.container.on(
            "drag",
            (e: Phaser.Input.Pointer, dragX: number, dragY: number) => {
                this._drag(e, dragX, dragY);
                if (this.onDrag !== undefined) {
                    this.onDrag(
                        {
                            type: "drag",
                            view: this,
                            event: e,
                        },
                        dragX,
                        dragY
                    );
                }
            }
        );
        // pointer, deltaX, deltaY, deltaZ

        this.container.on(
            "wheel",
            (
                pointer: Phaser.Input.Pointer,
                deltaX: number,
                deltaY: number,
                deltaZ: number
            ) => {
                if (this.onWheel !== undefined) {
                    this.onWheel(
                        {
                            type: "wheel",
                            view: this,
                            event: pointer,
                        },
                        deltaX,
                        deltaY
                    );
                }

                this.onScrollAreaWheel(pointer, deltaX, deltaY, deltaZ);
            }
        );
    }

    /**
     * 布局专用方法
     */
    editorPlace() {}

    get Width(): number {
        if (this.visible == false) return 0;
        return this.width;
    }
    get Height(): number {
        if (this.visible == false) return 0;
        return this.height;
    }

    getParentScrollTop(): number {
        if (this.parent == null) {
            return 0;
        }
        return this.parent.scrollTop;
    }

    get Top(): number {
        return this.top;
    }

    get Left(): number {
        return this.left;
    }

    set WidthRatio(value: number) {
        this.widthRatio = value;
        this.reSize();
        if (
            this.parent &&
            (this.parent.name === "QUIVerticalLayout" ||
                this.parent.name === "QUIHorizontalLayout")
        ) {
            this.parent.reLayout();
        }

        this.startLayout();
    }

    set HeightRatio(value: number) {
        this.heightRatio = value;
        this.reSize();
        if (
            this.parent &&
            (this.parent.name === "QUIVerticalLayout" ||
                this.parent.name === "QUIHorizontalLayout")
        ) {
            this.parent.reLayout();
        }
        this.startLayout();
    }

    get WidthRatio() {
        return this.widthRatio;
    }

    get HeightRatio() {
        return this.heightRatio;
    }
    reLayout() {}

    /**
     * 强制布局，用于在运行时修改布局参数后重新计算布局信息
     */
    forcedLayout() {
        this.startLayout();
        this.childViews.forEach((view) => {
            view.forcedLayout();
        });
    }

    set Width(value: number) {
        if (typeof value === "string") {
            value = parseInt(value);
        }
        this.width = value;
        if (this.width < this.miniWidth) {
            this.width = this.miniWidth;
        }

        this.reSize();
        if (
            this.parent &&
            (this.parent.name === "QUIVerticalLayout" ||
                this.parent.name === "QUIHorizontalLayout" ||
                this.parent.name === "QUIGridLayout" ||
                this.parent.name === "QUIScrollArea")
        ) {
            this.parent.reLayout();
        }

        this.startLayout();
    }
    set Height(value: number) {
        if (typeof value === "string") {
            value = parseInt(value);
        }
        this.height = value;
        if (this.height < this.miniHeight) {
            this.height = this.miniHeight;
        }

        this.reSize();
        if (
            this.parent &&
            (this.parent.name === "QUIVerticalLayout" ||
                this.parent.name === "QUIHorizontalLayout" ||
                this.parent.name === "QUIGridLayout" ||
                this.parent.name === "QUIScrollArea")
        ) {
            this.parent.reLayout();
        }
        this.startLayout();
    }

    set ScrollTop(value: number) {
        this.scrollTop = value;
        this.reSize();
    }

    set ScrollLeft(value: number) {
        this.scrollLeft = value;
        this.reSize();
    }

    set Top(value: number) {
        if (typeof value === "string") {
            value = parseInt(value);
        }
        this.top = value;
        this.container.y = this.top;

        this.bottom = undefined;
        this.reSize();
        if (this.parent && this.parent.name === "QUIScrollArea") {
            this.parent.reLayout();
        }
    }

    set Left(value: number) {
        if (typeof value === "string") {
            value = parseInt(value);
        }
        this.left = value;
        this.container.x = this.left;
        this.right = undefined;

        this.reSize();
        if (this.parent && this.parent.name === "QUIScrollArea") {
            this.parent.reLayout();
        }
    }

    set Right(value: number) {
        if (typeof value === "string") {
            value = parseInt(value);
        }
        this.right = value;
        this.reSize();
        if (this.parent && this.parent.name === "QUIScrollArea") {
            this.parent.reLayout();
        }
    }

    set Bottom(value: number) {
        if (typeof value === "string") {
            value = parseInt(value);
        }
        this.bottom = value;
        this.reSize();
        if (this.parent && this.parent.name === "QUIScrollArea") {
            this.parent.reLayout();
        }
    }

    set ImageUrl(value: string) {
        this.imageUrl = value;

        if (this.imageUrl == "" && this.image) {
            this.container.remove(this.image);
            this.image.destroy();
            this.image = null;
            return;
        }
        // this.imageKey = this.scene.qGame.getImageKey(this.imageUrl);
        // console.log("create image", this.imageUrl);
        if (this.image == null) {
            this.image = this.scene.add.image(0, 0, this.imageUrl);
            // this.image.width = this.width;
            // this.image.height = this.height;

            if (this.image) {
                this.image.setOrigin(0, 0);
                // this.image.setScale(this.image.width / )
                this.image.setDisplaySize(this.width, this.height);
                this.container.add(this.image);
                this.container.moveTo(this.image, 1);
                // this.container.bringToTop()
            }
        } else {
            this.image.setTexture(value);
            this.image.setDisplaySize(this.width, this.height);
        }
    }

    set Background(value: number | string) {
        this.backgroundValue = this.rgbUnify(value);
        this.createBackgroundCor();
    }

    get Background(): number {
        return this.backgroundValue;
    }

    set TempBackground(value: number | string) {
        this.tempBackgroundValue = this.rgbUnify(value);
        let temp = this.backgroundValue;
        this.backgroundValue = this.tempBackgroundValue;
        this.createBackgroundCor();
        this.backgroundValue = temp;
        this.tempBackgroundValue = this.rgbUnify(value);
    }
    public reSize(): this {
        if (this.rectangle) {
            this.rectangle.setTo(0, 0, this.width, this.height);
        }

        let parentWidth: number = 0;
        let parentHeight: number = 0;
        if (this.parent === null) {
            parentWidth = this.scene.cameras.main.width;
            parentHeight = this.scene.cameras.main.height;
        } else {
            const parent = this.parent as QUIView;

            if (
                parent.scrollYBarBackground &&
                parent.scrollYBarBackground.visible
            ) {
                parentWidth = parent.width - parent.scrollWidth;
            } else {
                parentWidth = parent.width;
            }

            if (
                parent.scrollXBarBackground &&
                parent.scrollXBarBackground.visible
            ) {
                parentHeight = parent.height - parent.scrollWidth;
            } else {
                parentHeight = parent.height;
            }
        }

        if (this.widthRatio > 0) {
            this.width = (parentWidth / 100) * this.widthRatio;
        }

        if (this.heightRatio > 0) {
            this.height = (parentHeight / 100) * this.heightRatio;
        }

        if (this.width > 0 && this.height > 0) {
            this.createBackgroundCor();
        }

        if (this.right !== undefined) {
            this.left = parentWidth - this.right - this.width;
        }
        if (this.bottom !== undefined) {
            this.top = parentHeight - this.bottom - this.height;
        }

        if (this.image) {
            this.image.setDisplaySize(this.width, this.height);
        }

        this.container.x = this.left - this.scrollLeft;
        this.container.y = this.top - this.scrollTop;

        // this.startLayout();

        this.childViews.forEach((view) => {
            view.reSize();
        });

        return this;
    }

    get ChildViews(): QUIView[] {
        return this.childViews;
    }

    // 布局方法（子类可以覆盖）
    layout() {
        // 默认不做任何布局，子类可以实现自己的布局逻辑
        this.childViews.forEach((view) => {
            view.layout();
        });
    }

    // 清除所有子视图
    public clearViews() {
        this.childViews.forEach((view) => {
            this.remove(view, true);
        });
        this.childViews = [];
    }

    get Container(): Phaser.GameObjects.Container {
        return this.container;
    }

    /**
     * 同级移动
     * @param index 目标位置的索引
     */
    public move(index: number) {
        if (this.parent === null) return;
        if (index >= 0 && index < this.parent.childViews.length) {
            const targetView = this.parent.childViews[index];
            const currentIndex = this.parent.childViews.indexOf(this);
            if (currentIndex !== -1) {
                this.childViews.splice(currentIndex, 1);
                this.childViews.splice(index, 0, this);
                this.container.remove(this.container);
                this.container.addAt(targetView.container, index);
            }
        }
    }

    public add(view: QUIView) {
        if (view.parent !== null) {
            view.parent.remove(view, false);
        }
        view.parent = this;
        this.childViews.push(view);
        this.container.add(view.container);
        // this.viewContainer.add(view.container);
        view.reSize();
        return this;
    }

    public adds(views: QUIView[]) {
        views.forEach((view) => {
            this.add(view);
        });
    }

    public remove(view: QUIView, destroy: boolean = false) {
        const index = this.childViews.indexOf(view);
        if (index !== -1) {
            this.childViews.splice(index, 1);
            this.container.remove(view.container);
            // this.viewContainer.remove(view.container);
            view.parent = null;
            if (destroy) {
                view.destroy();
            }
        }
    }

    public destroy() {
        if (this.manage.add === null) return;
        this.manage.add.removeNode(this);

        if (this.parent !== null) {
            this.parent.remove(this, false);
            this.parent = null;
        }

        this.container.destroy(true);

        if (this.image) {
            this.image.destroy(true);
        }
        if (this.backgoundColor) {
            this.backgoundColor.destroy(true);
        }
        if (this.mask) {
            this.mask.destroy(true);
        }
        if (this.rectangle) {
            this.rectangle = null;
        }
        if (this.scrollYBarBackground) {
            this.scrollYBarBackground.destroy(true);
        }
        if (this.scrollYBar) {
            this.scrollYBar.destroy(true);
        }
        if (this.scrollXBarBackground) {
            this.scrollXBarBackground.destroy(true);
        }
        if (this.scrollXBar) {
            this.scrollXBar.destroy(true);
        }
        this.childViews.forEach((view) => {
            view.destroy();
        });
    }

    set Visible(value: boolean) {
        this.container.visible = value;
        this.container.setVisible(value);
        if (this.visible) {
            this.reSize();
            if (
                this.parent &&
                (this.parent.name === "QUIVerticalLayout" ||
                    this.parent.name === "QUIHorizontalLayout" ||
                    this.parent.name === "QUIGridLayout" ||
                    this.parent.name === "QUIScrollArea")
            ) {
                this.parent.reLayout();
            }
            this.startLayout();
        }
    }

    get Visible(): boolean {
        return this.container.visible;
    }

    set BorderWidth(value: number) {
        this.borderWidth = value;
        this.createBackgroundCor();
    }

    set BorderColor(value: number | string) {
        value = this.rgbUnify(value);
        this.borderColor = value;
        this.createBackgroundCor();
    }

    // 创建背景（可选）
    protected createBackgroundCor() {
        if (this.backgoundColor) {
            this.container.remove(this.backgoundColor);
            this.backgoundColor.destroy();
        }

        this.backgoundColor = this.scene.add.graphics();
        this.backgoundColor.fillStyle(this.backgroundValue, this.alpha);
        this.backgoundColor.fillRect(0, 0, this.width, this.height);

        if (this.borderWidth > 0) {
            this.backgoundColor.lineStyle(this.borderWidth, this.borderColor);
            this.backgoundColor.strokeRect(
                0 + this.borderWidth / 2,
                0 + this.borderWidth / 2,
                this.width - this.borderWidth,
                this.height - this.borderWidth
            );
        }
        if (this.mask) {
            this.mask.clear();
            this.mask.fillRect(
                this.WorldX,
                this.WorldY,
                this.Width,
                this.Height
            );
        }
        this.container.add(this.backgoundColor);
        this.container.sendToBack(this.backgoundColor);
    }

    protected settingConfig(config: QUIViewConfig) {
        this.widthRatio = config.widthRatio || 0;
        this.heightRatio = config.heightRatio || 0;
        this.width = config.width || 0;
        this.height = config.height || 0;
        this.left = config.left || 0;
        this.top = config.top || 0;
        this.id = config.id || "";
        this.class = config.class || "";
        this.borderWidth = config.borderWidth || 0;
        this.alpha = config.alpha || 0;
        this.alignX = config.alignX || "left";
        this.alignY = config.alignY || "top";
        this.gap = config.gap || 0;
        this.paddingTop = config.paddingTop || 0;
        this.paddingBottom = config.paddingBottom || 0;
        this.paddingLeft = config.paddingLeft || 0;
        this.paddingRight = config.paddingRight || 0;
        this.prohibitEvent = config.prohibitEvent || false;

        if (config.borderColor) {
            this.borderColor = this.rgbUnify(config.borderColor);
        }
        if (config.right !== undefined) {
            this.right = config.right;
        }
        if (config.bottom !== undefined) {
            this.bottom = config.bottom;
        }
        if (config.background) {
            this.backgroundValue = this.rgbUnify(config.background) || 0x000000;
        }

        if (config.imageUrl) {
            this.imageUrl = config.imageUrl;
            // this.imageKey = this.scene.qGame.getImageKey(this.imageUrl);
            // console.log("create image", this.imageUrl);
            this.image = this.scene.add.image(0, 0, this.imageUrl);
            if (this.image) {
                this.image.setOrigin(0, 0);
            }
            // this.image.setDisplaySize(this.width, this.height);
        }

        this.miniHeight = 0;
        this.miniWidth = 0;
        if (config.miniHeight !== undefined) {
            this.miniHeight = config.miniHeight;
            if (this.height < this.miniHeight) {
                this.height = this.miniHeight;
            }
        }
        if (config.miniWidth !== undefined) {
            this.miniWidth = config.miniWidth;
            if (this.width < this.miniWidth) {
                this.width = this.miniWidth;
            }
        }
        if (config.maxHeight !== undefined) {
            this.maxHeight = config.maxHeight;
            if (this.height > this.maxHeight) {
                this.height = this.maxHeight;
            }
        }
        if (config.maxWidth !== undefined) {
            this.maxWidth = config.maxWidth;
            if (this.width > this.maxWidth) {
                this.width = this.maxWidth;
            }
        }

        this.onClick = config.onClick;
        this.onMouseDown = config.onMouseDown;
        this.onMouseUp = config.onMouseUp;
        this.onMouseOver = config.onMouseOver;
        this.onMouseOut = config.onMouseOut;
        this.onWheel = config.onWheel;
        this.onDrag = config.onDrag;
    }

    protected rgbUnify(value: number | string): number {
        if (typeof value === "string") {
            return Phaser.Display.Color.HexStringToColor(value).color;
        }
        return value;
    }

    public getViewAttribute(): QUIViewConfig {
        return {
            name: this.name,
            id: this.id,
            class: this.class,
            widthRatio: this.widthRatio,
            heightRatio: this.heightRatio,
            width: this.width,
            height: this.height,
            miniWidth: this.miniWidth,
            miniHeight: this.miniHeight,
            // maxWidth: this.maxWidth,
            // maxHeight: this.maxHeight,
            left: this.left,
            top: this.top,
            right: this.right,
            bottom: this.bottom,
            borderWidth: this.borderWidth,
            borderColor: this.borderColor,
            background: this.backgroundValue,
            alpha: this.alpha,
            alignX: this.alignX,
            alignY: this.alignY,
            gap: this.gap,
            paddingTop: this.paddingTop,
            paddingBottom: this.paddingBottom,
            paddingLeft: this.paddingLeft,
            paddingRight: this.paddingRight,
            imageUrl: this.imageUrl,
        };
    }

    public convertToXML() {
        const xml = document.createElement(this.name);
        const attributes = this.getViewAttribute() as QUIViewConfig;
        for (const key in attributes) {
            if (attributes.hasOwnProperty(key)) {
                const value = attributes[key];
                if (value !== undefined) {
                    switch (key) {
                        case "background":
                        case "borderColor":
                            xml.setAttribute(
                                key,
                                QGameFunction.ColorToHexString(value)
                            );
                            break;
                        default:
                            xml.setAttribute(key, value.toString());
                    }
                }
            }
        }

        this.childViews.forEach((view) => {
            const childXML = view.convertToXML();
            xml.appendChild(childXML);
        });
        return xml;
    }

    public findViewByID(id: string): QUIView | null {
        if (this.id === id) {
            return this;
        }
        for (const child of this.childViews) {
            const foundView = child.findViewByID(id);
            if (foundView) {
                return foundView;
            }
        }
        return null;
    }

    public findViewByClass(className: string): QUIView[] {
        const result: QUIView[] = [];
        if (this.class === className) {
            result.push(this);
        }
        for (const child of this.childViews) {
            const foundViews = child.findViewByClass(className);
            result.push(...foundViews);
        }
        return result;
    }

    public contains(x: number, y: number) {
        let _x = this.WorldX;
        let _y = this.WorldY;
        let w = this.Width;
        let h = this.Height;
        return Phaser.Geom.Rectangle.Contains(
            new Phaser.Geom.Rectangle(_x, _y, w, h),
            x,
            y
        );
    }
}
